package wili.demo.misc;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.IntStream;

import wili.c.Time9;

/**
 * 
 * @author weila 2021年11月30日
 */
class Stream_parallel_collect_demo {
	public static void test() throws InterruptedException { //https://www.cnblogs.com/puyangsky/p/7608741.html
		List<Integer> list0 = new ArrayList<>();
		List<Integer> list1 = new ArrayList<>();
		List<Integer> list2 = new ArrayList<>();
		List<Integer> list3 = new ArrayList<>();
		List<Integer> list4 = null;
		//List<Integer> list5 = new ArrayList<>();
		Lock lock = new ReentrantLock();
		int times = 100000;
		for (int i = 0; i < 10; i++) {
			if (i == 0) {
				{//感觉初次启动函数时会较慢。
					Time9.time(1, "-");
					IntStream.range(0, times).forEach(list0::add);
					Time9.time(-1, "-");
				}
			} else if (i == 1) {
				Time9.time(1, "a");//cost10,1,1
				IntStream.range(0, times).forEach(list1::add);
				Time9.time(-1, "a");
			} else if (i == 2) {
				Time9.time(1, "c");//cost6,28,26
				IntStream.range(0, times).parallel().forEach(j -> {
					lock.lock();
					try {
						list3.add(j);
					} finally {
						lock.unlock();
					}
				});
				Time9.time(-1, "c");
			} else if (i == 3) {
				Time9.time(1, "b");//cost9,9,8
				IntStream.range(0, times).parallel().forEach(list2::add);//并行产生问题了!
				Time9.time(-1, "b");
			} else if (i == 4) {
				Time9.time(1, "d");
				list4 = IntStream.range(0, times).parallel().collect(//并行+collect没产生问题
						ArrayList::new, (lis, e) -> lis.add(e), ArrayList::addAll);
				Time9.time(-1, "d");
			} else if (i == 5) {
			} else {
				break;
			}
		}
		Time9.print();
		System.out.println("a串行执行的大小：" + list1.size());
		System.out.println("b并行执行的大小：" + list2.size());
		System.out.println("c加锁并行执行的大小：" + list3.size());
		System.out.println("d,parallel().collect:" + list4.size());
	}

	public static void main(String[] args) throws InterruptedException {
		test();
	}
}
